const http = require('../../utils/http.js');
const app = getApp();
const { $Toast } = require('../../dist/base/index');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startX: 0, //开始坐标
    startY: 0,
    delBtnWidth: 65,
    list: [],
    totalPrice: 0, //总价
    allSelect: false, //默认不全选
  },

  //获取本地购物车列表
  getShopList() {
    var shopCar = wx.getStorageSync('shopCar1') || [];
    this.setData({
      list: shopCar
    });
    var ptf = app.globalData.platformFeer;
    this.setData({
      ptf
    })
    this.getTotal();
  },

  //计算总价
  getTotal() {
    var shopCar = this.data.list;
    var totalPrice = 0;
    var ptf=this.data.ptf/1;
    console.log(ptf)
    var shopCar1 = shopCar.filter((item, index) => {
      return item.is_select
    })
    shopCar1.forEach((item, index) => {
      totalPrice += (item.goods_nowprice * item.goods_sl);
    })
    this.setData({
      totalPrice: ptf + totalPrice
    })
  },

  //商品全选
  allSelect() {
    this.setData({
      allSelect: !this.data.allSelect
    })
    var shopCar = wx.getStorageSync('shopCar1') || [];

    if (this.data.allSelect == true) {
      shopCar.forEach((item, index) => {
        item.is_select = true
      })
      this.setData({
        list: shopCar
      })
    } else {
      shopCar.forEach((item, index) => {
        item.is_select = false
        this.setData({
          list: shopCar
        })
      })
    }

    this.getTotal();
  },

  //商品单选
  radioSelect(e) {
    var gid = e.currentTarget.dataset.id;
    console.log(gid)
    var shopCar = this.data.list;
    shopCar.some((item, index) => {
      if (gid == item.gid) {
        item.is_select = !item.is_select;
        return true;
      }
    })

    if (shopCar.every((item1, index1) => {
      return item1.is_select;
    })) {
      this.setData({
        allSelect: true
      })
    } else {
      this.setData({
        allSelect: false
      })
    }

    this.setData({
      list: shopCar
    })
    this.getTotal();
  },

  //商品数量加
  addNum(e) {
    var gid = e.currentTarget.dataset.id;
    var shopCar = this.data.list;
    shopCar.forEach((item, index) => {
      if (item.gid == gid) {
        item.goods_sl++
      }
    })
    this.setData({
      list: shopCar
    })
    wx.setStorageSync('shopCar1', shopCar);
    this.getTotal();
  },

  //商品数量减
  reduceNum(e) {
    var gid = e.currentTarget.dataset.id;
    var shopCar = this.data.list;
    shopCar.forEach((item, index) => {
      if (item.gid == gid) {
        item.goods_sl--
        if (item.goods_sl < 1) { item.goods_sl = 1 }
      }
    })
    this.setData({
      list: shopCar
    })
    wx.setStorageSync('shopCar1', shopCar);
    this.getTotal();
  },

  //删除
  delItem(e) {
    var gid = e.currentTarget.dataset.id;
    var shopCar = this.data.list;

    shopCar.forEach((item, index) => {
      if (item.gid == gid) {
        shopCar.splice(index, 1);
      }
    })
    this.setData({
      list: shopCar
    })
    this.getTotal();
    //更新缓存数据
    wx.setStorageSync('shopCar1', shopCar);
    if (shopCar.length==0){
      wx.removeStorageSync('totalPrice');
    }else{
      wx.setStorageSync('totalPrice', this.data.totalPrice);
    }
    
  },

  //清空购物车
  emptyItem() {
   
    wx.showModal({
      title: '提示',
      content: '确定清空购物车?',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            list: []
          })
          //更新缓存数据
          wx.removeStorageSync('shopCar1');
          // wx.setStorageSync('totalPrice', this.data.totalPrice);
          wx.removeStorageSync('totalPrice');
          wx.removeStorageSync('jiadanId');
        } else if (res.cancel) {

        }
      }
    })
  },

  touchS: function (e) {

    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },

  touchM: function (e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，说明向右滑动，文本层位置不变
        txtStyle = "left:0px;";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        list: list
      });
    }
  },
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        list: list
      });
    }
  },




  //立即支付
  payMoney() {
    var shopCar = this.data.list;
    if (shopCar.every((item, index) => {
      return !item.is_select
    })) {
     
      $Toast({
        content: '请选择商品!'
      });
      return
    } else {
      if (this.data.totalPrice-this.data.ptf/1<this.data.qisong/1){
        
        $Toast({
          content: `商品必须满${this.data.qisong}元才能配送!`,
          type: 'warning'
        });
        return;
      }

      var jiadanArr = shopCar.filter((item, index) => {
        return item.is_select;
      })
      var goods=[];
     jiadanArr.forEach((item,index)=>{
       goods.push({
         id:item.gid,
         num:item.goods_sl
       })
     })

      //加单订单生成
      var params = {
        uid: app.globalData.uid,
        accesstoken: app.globalData.token,
        goods:JSON.stringify(goods)
      }
      http.fetchApi('p_order_goods', params).then(res=>{
        if(res.data.code==1){
          var bl_order_id = res.data.results[0].bl_order_id;
          wx.setStorageSync('jiadanId', bl_order_id);
          //总价和商品存入缓存 
          wx.setStorageSync('totalPrice', this.data.totalPrice);
          wx.navigateBack({
            delta: 2
          })

        } else if (res.data.code == 2){
          
          $Toast({
            content: '该店已打样!',
            type: 'error'
          });
          return
        }else{
          $Toast({
            content: '服务器异常!',
            type: 'error'
          });
          return
        }
      })
     
     
    }

  },

  //获取加单起送费
  getAddQisong() {
    http.fetchApi('procedure_t', {
      p: 'R2012007'
    }).then(res => {
      if (res.data.code == 1) {
        var qisong = res.data.results[0].zd;
        this.setData({
          qisong
        })
      } else {
       
        $Toast({
          content: '网络连接失败!',
          type: 'error'
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAddQisong();
    this.getShopList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var shopCar1 = wx.getStorageSync('shopCar1') || [];
    shopCar1.forEach(item => {
      item.is_select = false
    })
    wx.setStorageSync('shopCar1', shopCar1)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})